package com.jc.service.common.interceptor;

import com.jc.service.common.exception.ServiceException;
import com.jc.service.common.model.UserContext;
import com.jc.service.common.model.LoginUser;
import com.jc.service.common.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT认证拦截器
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    public JwtAuthInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取Authorization
        String authHeader = request.getHeader("Authorization");
        
        // 检查是否存在Authorization头
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "未提供有效的认证令牌");
        }

        // 提取JWT令牌
        String token = authHeader.substring(7);
        
        // 验证令牌
        if (!jwtUtil.validateToken(token)) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "认证令牌已过期或无效");
        }

        // 从令牌中获取用户信息
        LoginUser loginUser = jwtUtil.getUserInfoFromToken(token);
        if (loginUser == null) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "无法从令牌中获取用户信息");
        }

        // 将用户信息存储到上下文中
        UserContext.setUser(loginUser);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除上下文中的用户信息，防止内存泄漏
        UserContext.clear();
    }
}